package com.asiainfo.iov.activity;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.asiainfo.iov.configs.ConstantsME;
import com.asiainfo.iov.configs.EventBusTag;
import com.asiainfo.iov.configs.InterfaceConfig;
import com.asiainfo.iov.entity.MessageInfo;
import com.asiainfo.iov.fragment.Fragment_homepage;
import com.asiainfo.iov.fragment.Fragment_personal;
import com.asiainfo.iov.networkModel.HttpUtil;
import com.asiainfo.iov.service.NotifyMessageService;
import com.framework.customviews.MyRadioGroupForAll;
import com.framework.utils.DownLoadManagerUtils;
import com.framework.utils.DownLoadObserver;
import com.framework.utils.PackageManagerUtil;
import com.framework.utils.PreferencesHelper;
import com.framework.utils.RequestPermissionsUtil;
import com.framework.utils.ScreenUtils;
import com.framework.utils.ToastUtil;
import com.framework.utils.Y;
import com.framework2.customviews.AutoFocusTextView;
import com.framework2.dialog.UpdateDialog;
import com.framework2.util.PicToastUtil;
import com.yaxin.yyt.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;

import butterknife.BindView;
import butterknife.ButterKnife;

public class HomepageActivity extends BaseActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
    @BindView(R.id.tv_title)
    TextView titleView;
    @BindView(R.id.iv_notify)
    ImageView ivNotify;
    @BindView(R.id.tv_count)
    TextView tvCount;
    @BindView(R.id.titleLayout)
    RelativeLayout titleLayout;
    @BindView(R.id.rb_1)
    RadioButton rb1;
    @BindView(R.id.rb_2)
    RadioButton rb2;
    @BindView(R.id.rg)
    MyRadioGroupForAll rg;
    //////////////////////
    private long exitTime;
    private int oldposition = -1;
    private Fragment findresult = null;
    // /////
    private Fragment Center_mContent;
    private Fragment fragment_1;
    private Fragment fragment_2;

    private boolean isShowLeft = true;//显示左边首页
    private MessageInfo messageInfo;
    private String updateContent;
    private String downLoadUrl;
    private String version;
    private ProgressHandler progressHandler = new ProgressHandler(this);
    private boolean requestPermissionMannual;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ScreenUtils.getInstance().setTranslucentStatus(this, true);
        ScreenUtils.getInstance().setStatusBarTintColor(this, getResources().getColor(R.color.white));
        setContentView(R.layout.activity_homepage_percent);
        ButterKnife.bind(this);
        initCompoundDrawable(0);
        initEvent();
//        initFragment();
        showFragment(0);
        startNewMessageService();
        requestUpdate();
    }

    private void requestUpdate() {

        try {
            HttpUtil.getInstance().requestVersionUpdate2(this, InterfaceConfig.checkUpdateUrl, new HttpUtil
                    .OnRequestResult<String>() {
                @Override
                public void onSuccess(String... t) {
                    if (null != t && t.length >= 4) {
                        int versionCodeFromServer = 0;
                        try {
                            versionCodeFromServer = Integer.parseInt(t[0]);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                        if (versionCodeFromServer > PackageManagerUtil.getInstance().getCurrentApkVersionCode
                                (HomepageActivity.this)) {
                            version = TextUtils.isEmpty(t[1]) ? "版本号未知" : t[1];
                            updateContent = TextUtils.isEmpty(t[2]) ? "版本号未知" : t[2];
                            downLoadUrl = TextUtils.isEmpty(t[3]) ? "http://www.baidu.com" : t[3];
                            new UpdateDialog(HomepageActivity.this).setUpdate(true).setContent(updateContent)
                                    .setDownLoadUrl(downLoadUrl).setVersion(version).showDialog(progressHandler);
                        }
                    }
                }

                @Override
                public void onFail(int code, String msg) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void startNewMessageService() {
        startService(new Intent(this, NotifyMessageService.class));
    }

    private void initFragment() {
        if (fragment_1 == null) {
            fragment_1 = new Fragment_homepage();
        }
        switchFragment(fragment_1, 0);
    }

    //eventBus通知新消息
    @Subscribe(threadMode = ThreadMode.MAIN, tag = "newMessage")
    public void receivedNewMessage(MessageInfo info) {
        messageInfo = info;
        onResume();
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_toast:
            case R.id.notifyLayout:
                PreferencesHelper.getInstance().putInfo(ConstantsME.hasNewMessage, false);
                findViewById(R.id.tv_toast).setVisibility(View.GONE);
                tvCount.setVisibility(View.INVISIBLE);
                if (messageInfo != null) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(ConstantsME.entity, messageInfo);
//                    startActivity(MessageCenterActivity.class, bundle);
                } else {
//                    startActivity(MessageCenterActivity.class);
                }
                break;
            default:
                break;
        }
    }

    private void initEvent() {
        rg.setOnCheckedChangeListener(new MyRadioGroupForAll.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(MyRadioGroupForAll group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_1:
                        showLeft(true);
                        showFragment(0);
//                        if (fragment_1 == null) {
//                            fragment_1 = new Fragment_homepage();
//                        }
//                        switchFragment(fragment_1, 0);
                        break;
                    case R.id.rb_2:
                        showLeft(false);
                        showFragment(1);
//                        if (fragment_2 == null) {
//                            fragment_2 = new Fragment_personal();
//                        }
//                        switchFragment(fragment_2, 1);
                        break;
                    default:
                        break;
                }
            }
        });
        rg.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (rg.getHeight() > 0) {
                    initCompoundDrawable(rg.getHeight());
                    rg.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
            }
        });
    }

    private void initCompoundDrawable(int heightAndWidth) {
        Drawable[] compoundDrawables = rb1.getCompoundDrawables();
        compoundDrawables[1].setBounds(0, 0, heightAndWidth > 0 ? (int) (heightAndWidth * 0.44) : ScreenUtils.getInstance().dip2px(this,
                25), heightAndWidth > 0 ? (int) (heightAndWidth * 0.44) : ScreenUtils.getInstance().dip2px(this, 25));
        rb1.setCompoundDrawables(compoundDrawables[0], compoundDrawables[1], compoundDrawables[2],
                compoundDrawables[3]);
        compoundDrawables = rb2.getCompoundDrawables();
        compoundDrawables[1].setBounds(0, heightAndWidth > 0 ? (int) (heightAndWidth * 0.44) * 6 / 44 : 10,
                heightAndWidth > 0 ? (int) (heightAndWidth * 0.44) : ScreenUtils.getInstance().dip2px(this, 25), heightAndWidth > 0 ? (
                        (int) (heightAndWidth * 0.44) - (int) (heightAndWidth * 0.44) * 6 / 44) : (ScreenUtils.getInstance().dip2px(this,
                        25) - 10));
        rb2.setCompoundDrawables(compoundDrawables[0], compoundDrawables[1], compoundDrawables[2],
                compoundDrawables[3]);

        rb1.setCompoundDrawablePadding(heightAndWidth > 0 ? heightAndWidth * 5 / 100 : 20);
        rb2.setCompoundDrawablePadding(heightAndWidth > 0 ? heightAndWidth * 11 / 100 : 40);
    }

    @Override
    protected void onResume() {
        super.onResume();
        showLeft(isShowLeft);
        if (!PreferencesHelper.getInstance().getBooleanData(ConstantsME.hasNewMessage)) {
            findViewById(R.id.tv_toast).setVisibility(View.GONE);
            tvCount.setVisibility(View.INVISIBLE);
        } else {
            findViewById(R.id.tv_toast).setVisibility(View.VISIBLE);
            tvCount.setVisibility(View.VISIBLE);
            ((AutoFocusTextView) findViewById(R.id.tv_toast)).setText(PreferencesHelper.getInstance().getStringData
                    (ConstantsME.newMessage));
        }
        if (getIntent().getBooleanExtra(ConstantsME.shouldRefresh, false)) {
            EventBus.getDefault().post("", EventBusTag.shouldRefresh);
        }
        if (requestPermissionMannual) {
            requestUpdate();
        }
        if (PreferencesHelper.getInstance().getBooleanData(ConstantsME.gotoHomepage)) {
            try {
                rg.check(R.id.rb_1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            PreferencesHelper.getInstance().putInfo(ConstantsME.gotoHomepage, false);
        }
    }

    /**
     * 显示左边fragment
     *
     * @param showLeft showLeft
     */
    private void showLeft(boolean showLeft) {
        if (null != titleView) {
            isShowLeft = showLeft;
            titleView.setText(getResources().getString(showLeft ? R.string.app_name : R.string.personalCenter));
            titleView.setTextColor(getResources().getColor(showLeft ? R.color.white : R.color._gray_dark));
            titleLayout.setBackgroundResource(showLeft ? R.color._blue : R.color.white);
            ivNotify.setImageResource(showLeft ? R.mipmap.icon_notify_white : R.mipmap.icon_notify);
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - this.exitTime > 2000L) {
                Toast.makeText(this.getApplicationContext(), this.getResources().getString(R.string.exist) + this
                        .getResources().getString(R.string.app_name), Toast.LENGTH_SHORT).show();
                this.exitTime = System.currentTimeMillis();
            } else {
                // 返回主界面
                /**
                 * 退出登录,清空数据
                 */
//                Intent intent_home = new Intent(Intent.ACTION_MAIN);
//                intent_home.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                intent_home.addCategory(Intent.CATEGORY_HOME);
//                startActivity(intent_home);
//                finish();
//                System.exit(0);
                ////////////////////
                int pid = Process.myPid();
                Process.killProcess(pid);
            }
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private void showFragment(int position) {
        FragmentTransaction ft = getSupportFragmentManager()
                .beginTransaction();
        if (position == 0 && fragment_1 == null) {
            fragment_1 = new Fragment_homepage();
            ft.add(R.id.relative_center_homepage, fragment_1);
        } else if (position == 1 && fragment_2 == null) {
            fragment_2 = new Fragment_personal();
            ft.add(R.id.relative_center_homepage, fragment_2);
        }
        if (position == 0) {
            ScreenUtils.getInstance().setTranslucentStatus(this, true);
            ScreenUtils.getInstance().setStatusBarTintColor(this, getResources().getColor(R.color._blue));
            if (fragment_2 != null) {
                ft.hide(fragment_2).show(fragment_1).commit();
            } else {
                ft.show(fragment_1).commit();
            }
        } else if (position == 1) {
            ScreenUtils.getInstance().setTranslucentStatus(this, true);
            ScreenUtils.getInstance().setStatusBarTintColor(this, getResources().getColor(R.color.white));
            if (fragment_1 != null) {
                ft.hide(fragment_1).show(fragment_2).commit();
            } else {
                ft.show(fragment_2).commit();
            }
        }
    }

    public void switchFragment(final Fragment fragment, final int position) {
        switchFragment(fragment, position, false);
    }

    public void switchFragment(final Fragment fragment, final int position, boolean mustReplace) {
        if (oldposition != position || mustReplace) {
            FragmentTransaction ft = getSupportFragmentManager()
                    .beginTransaction();
            findresult = getSupportFragmentManager().findFragmentByTag(
                    "viewid" + position);
            if (Center_mContent != null) {
                if (!mustReplace) {
                    ft.detach(Center_mContent);
                }
            }
            oldposition = position;
            if (findresult != null) {
                if (mustReplace) {
                    Center_mContent = fragment;
                    ft.replace(R.id.relative_center_homepage, Center_mContent, "viewid"
                            + position);
                } else {
                    ft.attach(findresult);
                    Center_mContent = findresult;
                }
            } else {
                Center_mContent = fragment;
                ft.add(R.id.relative_center_homepage, Center_mContent, "viewid"
                        + position);
            }
            ft.commitAllowingStateLoss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != progressHandler) {
            progressHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Y.y("Homepage--onRequestPermissionsResult:" + requestCode);
        if (requestCode == RequestPermissionsUtil.PERMISSION_WRITE_READ_EXTERNAL_STORAGE) {
            if ((grantResults.length > 1) && (grantResults[0] == PackageManager.PERMISSION_GRANTED) &&
                    (grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
                if (0 == DownLoadManagerUtils.getInstance().requestDownLoad(HomepageActivity.this,
                        downLoadUrl,
                        getResources().getString(R.string.app_name)
                                + version + ".apk",
                        getResources().getString(R.string.app_name) + "新版本"
                                + version, getResources().getString(R.string.app_name) + "新版本"
                                + version)) {
                    if (null != progressHandler) {
                        //监听下载进度条
                        getContentResolver().registerContentObserver(Uri.parse("content://downloads/"), true, new
                                DownLoadObserver(progressHandler, this,
                                PreferencesHelper.getInstance().getLongData(PreferencesHelper.getInstance()
                                        .getStringData(DownLoadManagerUtils.DownLoad_FileName))));
                    }
                    PicToastUtil.getInstance().showToast(HomepageActivity.this, "正在下载安装包，请稍后");
                }
            } else {
                ToastUtil.getInstance().showToast("存储权限未开启，请手动开启");
//                requestPermissionMannual = true;
                RequestPermissionsUtil.getInstance().showInstalledAppDetailSettingIntent(this, getPackageName());
            }
        }
    }

    /**
     * 防止内存溢出的内部静态handler
     */
    private static class ProgressHandler extends Handler {
        WeakReference<HomepageActivity> weakReference;

        ProgressHandler(HomepageActivity activity) {
            weakReference = new WeakReference<HomepageActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == DownLoadObserver.MESSAGE_PROGRESS) {
                int progress = msg.arg1;
//                ToastUtil.getInstance().showToast("新进度：" + progress);
                if (progress >= 100) {
                    String path = (String) msg.obj;
                    if (!TextUtils.isEmpty(path)) {
                        PackageManagerUtil.getInstance().installApk(weakReference.get(), path);
                    }
                }
            }
        }
    }
}
